/**
 * desc：常用工具函数
 * author：{yinwei}
 * date： {2018/6/27}
 */
import { Geolocation, addLocationListener, start, stop } from 'react-native-amap-geolocation';
import { NativeModules, PermissionsAndroid, Platform } from 'react-native';
import { IsNullOrEmpty, logger } from "./util";

const PI = 3.14159265358979324;
const x_pi = (3.14159265358979324 * 3000.0) / 180.0;

export default class MapUtils {
  //逆地理编码
  static regeo(location, callBack) {
    NetUtils.get(
      'https://restapi.amap.com/v3/geocode/regeo?location=' +
      location +
      '&radius=500&extensions=all&batch=false&roadlevel=0&key=' +
      KeyConstants.GaoDe_map_web,
      (success, json, message, status, response) => {
        callBack(success, json, message, status, response);
      },
    );
  }

  //地理编码 获取搜索位置
  static geo(address, callBack) {
    NetUtils.get(
      'https://restapi.amap.com/v3/geocode/geo?address=' +
      address +
      '&key=' +
      KeyConstants.GaoDe_map_web,
      (success, json, message, status, response) => {
        callBack(success, json, message, status, response);
      },
    );
  }

  //gps坐标转换 地图坐标
  static gpsToMap(locations, callBack) {
    NetUtils.get(
      'https://restapi.amap.com/v3/assistant/coordinate/convert?locations=' +
      locations +
      '&coordsys=mapbar&key=' +
      KeyConstants.GaoDe_map_web,
      (success, json, message, status, response) => {
        callBack(success, json, message, status, response);
      },
    );
  }

  //获取当前位置
  static getCurrentPosition(callBack) {
    Geolocation.getCurrentPosition(({ coords }) => {
      logger("=222222==11=>", coords)
      let latitude = MapUtils.longLatitude(coords.latitude, false);
      let longitude = MapUtils.longLatitude(coords.longitude, true);
      if (callBack) {
        callBack(latitude, longitude);
      }
    });
  }



  //根据缩放计算距离
  static countZoom(zoom) {
    if (zoom >= 19 && zoom <= 20) {
      return 10;
    }

    if (zoom >= 18 && zoom < 19) {
      return 25;
    }

    if (zoom >= 17 && zoom < 18) {
      return 50;
    }

    if (zoom >= 16 && zoom < 17) {
      return 100;
    }

    if (zoom >= 15 && zoom < 16) {
      return 200;
    }

    if (zoom >= 14 && zoom < 15) {
      return 500;
    }

    if (zoom >= 13 && zoom < 14) {
      return 1000;
    }

    if (zoom >= 12 && zoom < 13) {
      return 2000;
    }

    if (zoom >= 11 && zoom < 12) {
      return 5000;
    }

    if (zoom >= 10 && zoom < 11) {
      return 10000;
    }

    if (zoom >= 9 && zoom < 10) {
      return 20000;
    }

    if (zoom >= 8 && zoom < 9) {
      return 30000;
    }

    if (zoom >= 7 && zoom < 8) {
      return 50000;
    }

    if (zoom >= 6 && zoom < 7) {
      return 100000;
    }

    if (zoom >= 5 && zoom < 6) {
      return 200000;
    }

    if (zoom >= 4 && zoom < 5) {
      return 500000;
    }

    if (zoom >= 2 && zoom < 4) {
      return 1000000;
    }

    return 1000;
  }

  /*
   * 处理经纬度数据 小数点保留六位
   * 经度范围 -180 ~ 180
   * 纬度范围 -90 ~ 90
   * 超出方位 返回0度
   *
   */
  static longLatitude(longLatVal, isLongitude) {
    //处理NaN类型
    const longlat = parseFloat(longLatVal);
    if (isNaN(longlat)) {
      return 0;
    }

    // 经度范围 -180 ~ 180 ;纬度范围 -90 ~ 90
    const range = isLongitude ? 180 : 90;
    if (Math.abs(longlat) > range) {
      return 0;
    }

    //小数点保留六位
    if (longlat.toString().indexOf('.') > 0) {
      const longlatsplit = longLatVal.toString().split('.');
      if (longlatsplit.length >= 2) {
        return (
          parseFloat(longlatsplit[0] === '' ? 0 : longlatsplit[0]) +
          parseFloat('.' + longlatsplit[1].slice(0, 6))
        );
      }
    }

    return longlat;
  }
  //更新当前位置
  static updateCenterPosition() {
    console.log('获取位置1')
    start();
    addLocationListener(coords => {
      console.log('获取位置', coords)
      if (!IsNullOrEmpty(coords)) {
        stop();
        // Constants.centerLatitude = MapUtils.longLatitude(coords.latitude, false);
        // Constants.centerLongitude = MapUtils.longLatitude(coords.longitude, true);
      }
    });

    // Geolocation.getCurrentPosition=(success,error) => {
    //   console.log('获取位置',success)
    //   console.log('获取位置错误',error)
    //   // Constants.centerLatitude = MapUtils.longLatitude(coords.latitude, false);
    //   // Constants.centerLongitude = MapUtils.longLatitude(coords.longitude, true);
    // };
  }

  static transformLat(x, y) {
    var ret =
      -100.0 +
      2.0 * x +
      3.0 * y +
      0.2 * y * y +
      0.1 * x * y +
      0.2 * Math.sqrt(Math.abs(x));
    ret +=
      ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) /
      3.0;
    ret +=
      ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0;
    ret +=
      ((160.0 * Math.sin((y / 12.0) * PI) + 320 * Math.sin((y * PI) / 30.0)) *
        2.0) /
      3.0;
    return ret;
  }
  static transformLon(x, y) {
    var ret =
      300.0 +
      x +
      2.0 * y +
      0.1 * x * x +
      0.1 * x * y +
      0.1 * Math.sqrt(Math.abs(x));
    ret +=
      ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) /
      3.0;
    ret +=
      ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0;
    ret +=
      ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) *
        2.0) /
      3.0;
    return ret;
  }
  // 坐标转换
  static delta(lat, lon) {
    var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
    var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
    var dLat = this.transformLat(lon - 105.0, lat - 35.0);
    var dLon = this.transformLon(lon - 105.0, lat - 35.0);
    var radLat = (lat / 180.0) * PI;
    var magic = Math.sin(radLat);
    magic = 1 - ee * magic * magic;
    var sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * PI);
    dLon = (dLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * PI);
    return { lat: dLat, lon: dLon };
  }
  // 判断是否为国外坐标
  static outOfChina(lat, lon) {
    if (lon < 72.004 || lon > 137.8347) {
      return true;
    }
    if (lat < 0.8293 || lat > 55.8271) {
      return true;
    }
    return false;
  }
  // GPS---高德
  static gcj_encrypt(wgsLat, wgsLon) {
    wgsLat = parseFloat(wgsLat);
    wgsLon = parseFloat(wgsLon);
    if (this.outOfChina(wgsLat, wgsLon)) {
      return { latitude: wgsLat, longitude: wgsLon };
    }

    var d = this.delta(wgsLat, wgsLon);
    return { latitude: wgsLat + d.lat, longitude: wgsLon + d.lon };
  }

  static async requestPermission(callBack) {
    try {
      const granted = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      ]);

      if (
        granted[PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION] ===
        PermissionsAndroid.RESULTS.GRANTED &&
        granted[PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION] ===
        PermissionsAndroid.RESULTS.GRANTED
      ) {
        callBack();
      }
    } catch (err) {
      console.warn(err);
    }
  }

  static async checkAndroidPermission(callBack) {
    try {
      const grantedCamera = await PermissionsAndroid.check(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      );

      const grantedRead = await PermissionsAndroid.check(
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      );

      if (grantedCamera && grantedRead) {
        callBack();
      } else {
        this.requestPermission(callBack);
      }
    } catch (err) {
      console.warn(err);
    }
  }
}
